import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/server_config.dart';
import '../providers/vpn_provider.dart';
import '../services/ip_location_service.dart';

/// 显示Ping测试进度的对话框
class PingTestDialog extends StatefulWidget {
  final ServerConfig server;

  const PingTestDialog({
    super.key,
    required this.server,
  });

  @override
  State<PingTestDialog> createState() => _PingTestDialogState();
}

class _PingTestDialogState extends State<PingTestDialog> {
  bool _isCompleted = false;
  String _statusText = 'Initializing...';
  IconData _statusIcon = Icons.hourglass_empty;
  Color _statusColor = Colors.blue;

  @override
  void initState() {
    super.initState();
    _runTest();
  }

  Future<void> _runTest() async {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
    
    try {
      // 步骤1: 测试延迟
      setState(() {
        _statusText = 'Testing connection...';
        _statusIcon = Icons.speed;
        _statusColor = Colors.blue;
      });
      await Future.delayed(const Duration(milliseconds: 500));
      
      // 步骤2: 获取位置信息
      setState(() {
        _statusText = 'Getting location info...';
        _statusIcon = Icons.public;
        _statusColor = Colors.orange;
      });
      
      await vpnProvider.testPing(widget.server);
      
      // 检查测试结果
      final updatedServer = vpnProvider.servers
          .firstWhere((s) => s.id == widget.server.id);
      
      if (updatedServer.ping < 0) {
        // Ping失败
        setState(() {
          _statusText = 'Connection test failed!';
          _statusIcon = Icons.error_outline;
          _statusColor = Colors.red;
          _isCompleted = true;
        });
      } else {
        // 步骤3: 完成
        setState(() {
          _statusText = 'Test completed!';
          _statusIcon = Icons.check_circle;
          _statusColor = Colors.green;
          _isCompleted = true;
        });
      }
      
      // 等待一下再关闭
      await Future.delayed(const Duration(milliseconds: 1200));
      if (mounted) {
        Navigator.of(context).pop();
      }
    } catch (e) {
      setState(() {
        _statusText = 'Test failed: ${e.toString()}';
        _statusIcon = Icons.error;
        _statusColor = Colors.red;
        _isCompleted = true;
      });
      
      await Future.delayed(const Duration(seconds: 2));
      if (mounted) {
        Navigator.of(context).pop();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final ipLocationService = IpLocationService();
    final countryFlag = widget.server.countryCode != null 
        ? ipLocationService.getCountryFlag(widget.server.countryCode!)
        : null;

    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 服务器信息
            Row(
              children: [
                if (countryFlag != null) ...[
                  Text(
                    countryFlag,
                    style: const TextStyle(fontSize: 32),
                  ),
                  const SizedBox(width: 12),
                ],
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.server.name,
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      if (widget.server.country != null)
                        Text(
                          widget.server.city != null 
                              ? '${widget.server.city}, ${widget.server.country}'
                              : widget.server.country!,
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey.shade600,
                          ),
                        ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 24),
            
            // 状态指示器
            AnimatedContainer(
              duration: const Duration(milliseconds: 300),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: _statusColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: _statusColor.withOpacity(0.3),
                  width: 2,
                ),
              ),
              child: Column(
                children: [
                  AnimatedSwitcher(
                    duration: const Duration(milliseconds: 300),
                    child: Icon(
                      _statusIcon,
                      key: ValueKey(_statusIcon),
                      size: 48,
                      color: _statusColor,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Text(
                    _statusText,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      color: _statusColor,
                    ),
                  ),
                  if (!_isCompleted) ...[
                    const SizedBox(height: 12),
                    SizedBox(
                      width: 24,
                      height: 24,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation(_statusColor),
                      ),
                    ),
                  ],
                ],
              ),
            ),
            
            // Ping结果（如果已有）
            Consumer<VpnProvider>(
              builder: (context, vpnProvider, _) {
                final updatedServer = vpnProvider.servers
                    .firstWhere((s) => s.id == widget.server.id);
                
                if (_isCompleted) {
                  if (updatedServer.ping < 0) {
                    // 显示失败信息
                    return Column(
                      children: [
                        const SizedBox(height: 16),
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Theme.of(context).brightness == Brightness.dark
                                ? Colors.red.shade900.withOpacity(0.2)
                                : Colors.red.shade50,
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(
                              color: Theme.of(context).brightness == Brightness.dark
                                  ? Colors.red.shade700.withOpacity(0.5)
                                  : Colors.red.shade200,
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.signal_wifi_off,
                                size: 20,
                                color: Colors.red.shade700,
                              ),
                              const SizedBox(width: 8),
                              Text(
                                'Connection Failed',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.red.shade700,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    );
                  } else {
                    // 显示成功的ping结果
                    return Column(
                      children: [
                        const SizedBox(height: 16),
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Colors.grey.shade100,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.network_ping,
                                size: 20,
                                color: _getPingColor(updatedServer.ping),
                              ),
                              const SizedBox(width: 8),
                              Text(
                                '${updatedServer.ping} ms',
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                  color: _getPingColor(updatedServer.ping),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    );
                  }
                }
                return const SizedBox.shrink();
              },
            ),
          ],
        ),
      ),
    );
  }

  Color _getPingColor(int ping) {
    if (ping < 50) return Colors.green;
    if (ping < 100) return Colors.orange;
    return Colors.red;
  }
}
